package com.tql.mall.sms.service.impl;

import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.tql.mall.sms.key.Key;
import com.tql.mall.sms.service.SmsService;
import com.tql.mall.sms.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 使用阿里云短信服务，发送验证码
     *
     * @param phone
     * @return
     */
    @Override
    public boolean sendCode(String phone) throws Exception {

        //如果缓存中含有该手机号对应的验证码，就不会发送
        if (!StringUtils.isEmpty(redisTemplate.opsForValue().get(phone))) {
            System.out.println("5分钟内不重复发送！");
            return false;
        }

        boolean flag = false;
        //生成随机4位数字验证码
        String code = RandomUtil.getFourBitRandom();

        // 工程代码泄露可能会导致AccessKey泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html
        com.aliyun.dysmsapi20170525.Client client = SmsServiceImpl.createClient(Key.AccessKey, Key.AccessKeySecret);
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setSignName("tqlmall")
                .setTemplateCode("SMS_461370247")
                .setPhoneNumbers(phone)
                .setTemplateParam("{\"code\":\"" + code + "\"}");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            SendSmsResponse response = client.sendSmsWithOptions(sendSmsRequest, runtime);
            System.out.println(response.getBody());
            System.out.println("message:" + response.getBody().message);
            System.out.println("code:" + response.getBody().code);
            if (response.getBody().getMessage().equals("OK") && response.getBody().getCode().equals("OK")) {
                flag = true;
            }
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        //验证码发送成功，则将验证码保存到Redis
        if (flag) {
            //键为手机号，值为生成的验证码，并且设置过期的时间
            //过期时间 5 分钟
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
        }
        return flag;
    }

    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

}
